<template>
  <main @keyup.enter="submitForm">
    <el-form
      :model="codeForm"
      :rules="rules"
      status-icon
      ref="codeForm"
      class="codeForm"
    >
      <el-form-item prop="phoneNum">
        <el-input
          prefix-icon="el-icon-mobile"
          placeholder="请输入手机号"
          @input="limitPhoneNum"
          type="number"
          v-model="codeForm.phoneNum"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item prop="msgCode">
        <el-input
          prefix-icon="el-icon-message"
          placeholder="请输入验证码"
          type="number"
          class="msg-code"
          @input="limitCodeNum"
          v-model="codeForm.msgCode"
          autocomplete="off"
        ></el-input>
        <span
          @click="sendCode()"
          :class="'send-code' + (isSendCodeActive ? ' is-active' : '')"
          >{{ sendMsg }}</span
        >
      </el-form-item>
      <div class="operate-pass">
        <el-checkbox v-model="agreeDoc">阅读并接受</el-checkbox>
        <a style="color: #0080ff" @click="openDoc">《荣大科技用户协议》</a>
      </div>
      <el-form-item>
        <el-button
          type="primary"
          @click="submitForm('codeForm')"
          :disabled="isBadSubmit"
          :loading="loading"
          >{{ submitText }}</el-button
        >
      </el-form-item>
      <div class="hint-tail">
        <span>验证即登录，未注册将自动创建智慧云账号</span>
      </div>
    </el-form>
  </main>
</template>

<script>
import { getRSAKey, sendAuthCode } from 'api/modules/login.api';
import { loginByMobile } from 'api/modules/loginMobile.api';

// 验证码计时器倒计时时间
const COUNT_DOWN_NUMBER = 60;

export default {
  name: 'vertify-code',
  data() {
    const validatePhone = (rule, value, callback) => {
      // this.badPhoneNum = true;
      if (!value) {
        return callback(new Error('手机号不能为空'));
      }
      setTimeout(() => {
        if (!this.phoneNumLegal(this.codeForm.phoneNum)) {
          callback(new Error('请输入有效的手机号码'));
        } else {
          this.badPhoneNum = false;
          callback();
        }
      }, 10);
    };
    return {
      codeForm: {
        phoneNum: '',
        msgCode: '',
      },
      countDownNum: COUNT_DOWN_NUMBER,
      agreeDoc: false,
      rules: {
        phoneNum: [{ validator: validatePhone, trigger: 'blur' }],
      },
      timeObj: {},
      loading: false,
      badPhoneNum: true,
      sendMsg: '发送验证码',
      sendCodeLoaing: false,
    };
  },
  watch: {
    'codeForm.phoneNum': {
      handler(newVal) {
        this.badPhoneNum = !this.phoneNumLegal(newVal);
      },
    },
  },
  computed: {
    // 判断发送验证码是否可点
    isSendCodeActive() {
      return (
        // 如果时间归零 或 未开始计时， 发送验证码按钮可点
        (this.countDownNum === 0 || this.countDownNum === COUNT_DOWN_NUMBER) &&
        !this.badPhoneNum &&
        !this.sendCodeLoaing
      );
    },
    // 判断是否登录可点击
    isBadSubmit() {
      return !this.codeForm.msgCode || this.badPhoneNum;
    },
  },
  props: {
    submitText: {
      type: String,
      default: '提交',
    },
    linkFlag: {
      type: Boolean,
      default: false,
    },
    notUseLoginPost: {
      type: Boolean,
      default: false,
    },
  },
  beforeDestroy() {
    clearTimeout(this.timeObj.codeCount);
  },
  mounted() {},
  methods: {
    openDoc() {
      window.open(
        'http://ibsaas-crm.rongdasoft.com:19002/registAgreement',
        '__blank'
      );
    },
    submitForm() {
      // 如果格式不正确，就不允许登录 (防止回车登录的)
      if (this.isBadSubmit) {
        return;
      }
      if (!this.agreeDoc) {
        this.$message.error('请先勾选并同意荣大科技用户协议');
        return;
      }
      this.handleLogin();
    },
    async handleLogin() {
      this.loading = true;
      const { phoneNum, msgCode } = this.codeForm;
      const params = {
        data: {
          mobile: phoneNum,
          authCode: msgCode,
          linkFlag: this.linkFlag,
        },
        loginType: 'web',
      };
      this.$set(params, 'mode', 'codeLogin');
      this.$emit('beforeLogin', params);
      if (this.notUseLoginPost) {
        return;
      }
      const response = await loginByMobile(params);
      const { msg, code } = response;
      if (code !== 0) {
        this.$message.error(msg);
        this.loading = false;
      }
      this.$emit('submitForm', response);
    },
    // 没有publicKeyCode，重新获取
    async rsaFailure() {
      const { data } = await getRSAKey();
      if (!data) {
        this.$message.error('系统异常，请刷新重试');
        return;
      }
      this.sendCode(data);
    },
    // 发送验证码
    async sendCode(newKeyCode = undefined) {
      if (!this.isSendCodeActive) {
        return;
      }
      this.sendCodeLoaing = true;
      if (!this.globalProcessData.getPublicKey() && !newKeyCode) {
        // 没有publicKeyCode，重新获取
        this.rsaFailure();
        return;
      }
      const params = {
        data: {
          mobile: this.codeForm.phoneNum,
        },
      };
      const request = this.$loginUtils.handleEncryptionRequest(
        params,
        // 如果公钥不存在则使用刷新的公钥
        newKeyCode || this.globalProcessData.getPublicKey()
      );
      const response = await sendAuthCode(request).catch(() => {});
      if (response.code !== 0) {
        this.$message({
          message: response.msg,
          type: 'error',
        });
        this.sendCodeLoaing = false;
        return;
      }
      this.$message({
        message: '验证码已发送',
        type: 'success',
      });
      if (this.timeObj.codeCount) {
        clearTimeout(this.timeObj.codeCount);
      }
      this.countDownFn(this.countDownNum);
    },
    limitPhoneNum(value) {
      if (value.toString().length > 11) {
        this.codeForm.phoneNum = this.codeForm.phoneNum.toString().slice(0, 11);
      }
    },
    limitCodeNum(value) {
      if (value.toString().length > 6) {
        this.codeForm.msgCode = this.codeForm.msgCode.toString().slice(0, 6);
      }
    },
    // 倒计时
    countDownFn(time) {
      this.countDownNum = time;
      if (time === 0) {
        this.sendMsg = '重新发送';
        this.countDownNum = COUNT_DOWN_NUMBER;
        this.sendCodeLoaing = false;
        return;
      }
      this.countDownNum--;
      this.sendMsg = `${this.countDownNum}秒后可重发`;
      this.timeObj.codeCount = setTimeout(() => {
        this.countDownFn(this.countDownNum);
      }, 1000);
    },
    // 判断手机号是否合法
    phoneNumLegal(str) {
      const check = /^1[3456789]\d{9}$/;
      return check.test(str);
    },
  },
};
</script>

<style lang="less" scoped>
.hint-tail {
  text-align: center;
  font-weight: 400;
  font-size: 12px;
  color: #909399;
}
.msg-code {
  position: relative;
}
.send-code {
  position: absolute;
  right: 12px;
  cursor: not-allowed;
  font-family: MicrosoftYaHei;
  font-size: 12px;
  color: #909399;
}
.is-active {
  color: #0062ff;
  cursor: pointer;
}
</style>

<style lang="less">
.codeForm {
  .operate-pass {
    color: #606266;
    > a {
      cursor: pointer;
      font-size: 12px;
    }
    margin-bottom: 24px;
    .el-checkbox__label {
      font-size: 12px;
    }
    .el-checkbox__input.is-checked + .el-checkbox__label {
      color: #606266;
    }
  }
}
</style>
